package com.yl.order.ui.fragment;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.ColorStateList;
import android.content.res.Resources;
import android.graphics.Color;
import android.support.annotation.NonNull;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.helper.ItemTouchHelper;
import android.text.TextUtils;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.DecodeFormat;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.load.resource.bitmap.CenterCrop;
import com.bumptech.glide.request.RequestOptions;
import com.jeremyliao.liveeventbus.LiveEventBus;
import com.yl.common.ui.BaseFragment;
import com.yl.order.Constants;
import com.yl.order.R;
import com.yl.order.db.entity.CategoryEntity;
import com.yl.order.db.entity.GoodsEntity;
import com.yl.order.db.entity.OrderGoodsEntity;
import com.yl.order.db.entity.ProductEntity;
import com.yl.order.db.entity.SpecEntity;
import com.yl.order.interfaces.ItemTouchCallback;
import com.yl.order.model.SyncModel;
import com.yl.order.ui.adapter.BaseMoveAdapter;
import com.yl.order.ui.component.GridDividerItemDecoration;
import com.yl.order.ui.component.LinearDividerItemDecoration;
import com.yl.order.ui.dialog.SpecSelectDialogFragment2;
import com.yl.order.utils.CornersRoundedTransformation;
import com.yl.order.utils.OrderUtils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Set;

import io.reactivex.schedulers.Schedulers;

/**
 * create by cjx on 2024/5/14
 * desc:
 */
public class MainOrderFragment extends BaseFragment {

    private ShopCartFragment shopCartFragment;

    private GroupAdapter groupAdapter;
    private GoodsAdapter productAdapter;

    private HashMap<String, ArrayList<GoodsEntity>> goodsMap;

    public static MainOrderFragment newInstance() {
        return new MainOrderFragment();
    }

    @Override
    public int getViewId() {
        return R.layout.fragment_main_order;
    }

    @Override
    public void afterViewShow() {

        FragmentTransaction transaction = getChildFragmentManager().beginTransaction();
        shopCartFragment = ShopCartFragment.newInstance();
        transaction.add(R.id.shop_cart_container, shopCartFragment);
        transaction.commitNow();

        RecyclerView groupView = findViewById(R.id.group_container);
        RecyclerView productView = findViewById(R.id.formula_container);

        SyncModel.getAllGoodsList(goodsEntities -> {
            Context context = getContext();
            if (context == null) {
                return;
            }
            goodsMap = new HashMap<>();
            for (GoodsEntity g : goodsEntities) {
                ArrayList<GoodsEntity> list = goodsMap.get(g.getGroupNumber());
                if (list == null) {
                    list = new ArrayList<>(4);
                    list.add(g);
                    goodsMap.put(g.getGroupNumber(), list);
                } else {
                    list.add(g);
                }
            }

            Set<String> groupSet = goodsMap.keySet();
            ArrayList<CategoryEntity> allMenu = SyncModel.getProductCategoryList();
            ArrayList<CategoryEntity> menus = new ArrayList<>(allMenu.size());
            for (CategoryEntity c : allMenu) {
                if (groupSet.contains(c.getNumber())) {
                    menus.add(c);
                }
            }
            productView.postDelayed(() -> {
                int viewWidth = productView.getWidth();
                int dividerSize = getResources().getDimensionPixelSize(R.dimen.dp_4);
                groupView.setLayoutManager(new LinearLayoutManager(context));

                groupView.addItemDecoration(new LinearDividerItemDecoration(LinearLayoutManager.VERTICAL, dividerSize, Color.TRANSPARENT));
                groupAdapter = new GroupAdapter(menus, context, v -> {
                    int tag = (int) v.getTag();
                    if (tag == groupAdapter.selectPosition) {
                        return;
                    }
                    groupAdapter.updatePosition(tag);
                    String groupNumber = groupAdapter.menus.get(groupAdapter.selectPosition).getNumber();
                    ArrayList<GoodsEntity> productList = goodsMap.get(groupNumber);
                    productAdapter.updateList(productList);
                });
                ItemTouchHelper productTouchHelper = new ItemTouchHelper(new ItemTouchCallback(groupAdapter, (from, to) -> {
                    int sort = 0;
                    for (CategoryEntity e : groupAdapter.menus) {
                        e.setSort(sort++);
                    }
                    Schedulers.io().scheduleDirect(() -> SyncModel.updateGroupList(groupAdapter.menus));
                }));
                productTouchHelper.attachToRecyclerView(groupView);
                groupView.setAdapter(groupAdapter);

                // 显示产品
                int specCount = (viewWidth - dividerSize) / (getResources().getDimensionPixelSize(R.dimen.dp_100) + dividerSize);
                productView.setLayoutManager(new GridLayoutManager(context, specCount));
                productView.setPadding(dividerSize, dividerSize, dividerSize, dividerSize);
                productView.addItemDecoration(new GridDividerItemDecoration(dividerSize));
                ArrayList<GoodsEntity> productList = menus.isEmpty() ? null : goodsMap.get(menus.get(0).getNumber());
                int itemWidth = (viewWidth - dividerSize) / specCount;
                productAdapter = new GoodsAdapter(productList, itemWidth, dividerSize, v -> {
                    GoodsEntity goods = (GoodsEntity) v.getTag();
                    showSpecSelectDialog(goods);
                });
                productTouchHelper = new ItemTouchHelper(new ItemTouchCallback(productAdapter, (from, to) -> {
                    int sort = 0;
                    for (GoodsEntity e : productAdapter.goodsList) {
                        e.setSort(sort++);
                    }
                    Schedulers.io().scheduleDirect(() -> SyncModel.updateGoodsList(productAdapter.goodsList));
                }));
                productTouchHelper.attachToRecyclerView(productView);
                productView.setAdapter(productAdapter);

            }, 40);
        });

        registerEvent();
    }

    @SuppressLint("NotifyDataSetChanged")
    private void registerEvent() {
        LiveEventBus.get(Constants.BUS_PRODUCT_GROUP_UPDATE).observe(this, o -> {
            SyncModel.getAllGoodsList(goodsEntities -> {
                Context context = getContext();
                if (context == null) {
                    return;
                }
                goodsMap = new HashMap<>();
                for (GoodsEntity g : goodsEntities) {
                    ArrayList<GoodsEntity> list = goodsMap.get(g.getGroupNumber());
                    if (list == null) {
                        list = new ArrayList<>(4);
                        list.add(g);
                        goodsMap.put(g.getGroupNumber(), list);
                    } else {
                        list.add(g);
                    }
                }

                Set<String> groupSet = goodsMap.keySet();
                ArrayList<CategoryEntity> allMenu = SyncModel.getProductCategoryList();
                ArrayList<CategoryEntity> menus = new ArrayList<>(allMenu.size());
                for (CategoryEntity c : allMenu) {
                    if (groupSet.contains(c.getNumber())) {
                        menus.add(c);
                    }
                }
                groupAdapter.init(menus);
                groupAdapter.notifyDataSetChanged();

                String groupNumber = groupAdapter.menus.get(groupAdapter.selectPosition).getNumber();
                ArrayList<GoodsEntity> productList = goodsMap.get(groupNumber);
                productAdapter.updateList(productList);
            });
        });
    }

    // 选择规格弹窗
    private void showSpecSelectDialog(GoodsEntity goods) {
        ArrayList<ProductEntity> productList = SyncModel.getProductList(goods.getNumber());
        if (productList.isEmpty()) {
            String tip = String.format(getString(R.string.order_not_product_format), goods.getName());
            showToast(tip);
            return;
        }
        ArrayList<HashSet<String>> specSetList = new ArrayList<>();
        HashSet<String> defaultSpec = null;
        for (ProductEntity e : productList) {
            String[] split = e.getSpecNumber().split(",");
            HashSet<String> set = new HashSet<>(Arrays.asList(split));
            specSetList.add(set);
            if (e.getIsDefault()) {
                defaultSpec = set;
            }
        }
        SpecSelectDialogFragment2.newInstance(goods, specSetList, defaultSpec, specs -> {
                    StringBuilder specNumberBuilder = new StringBuilder();
                    for (SpecEntity s : specs) {
                        specNumberBuilder.append(",").append(s.getNumber());
                    }
                    ProductEntity product = SyncModel.getProductByGoodsSpec(goods.getNumber(), specNumberBuilder.substring(1));
                    OrderGoodsEntity orderGoods = new OrderGoodsEntity(null, null, "1", product.getProductNumber(),
                            product.getGoodsName(), product.getGoodsNumber(), goods.getIcon(), product.getSpecNumber(), product.getSpecName(),
                            null, TextUtils.isEmpty(product.getPrice()) ? "0" : product.getPrice(), 1, 0, 0, null, null, 0);
                    shopCartFragment.addGoods(orderGoods);
                })
                .show(getChildFragmentManager(), "spec_select");
    }

    private static class GroupAdapter extends BaseMoveAdapter<CategoryEntity> {
        private ArrayList<CategoryEntity> menus;
        private final View.OnClickListener listener;
        private int selectPosition = 0;

        private final int textSize;
        private final int height;
        private final ColorStateList colorStateList;

        public GroupAdapter(ArrayList<CategoryEntity> menus, Context context, View.OnClickListener listener) {
            this.listener = listener;
            Resources resources = context.getResources();
            this.colorStateList = resources.getColorStateList(R.color.button_text_color);
            this.textSize = resources.getDimensionPixelSize(R.dimen.sp_11);
            this.height = resources.getDimensionPixelSize(R.dimen.dp_36);
            init(menus);
        }

        public void init(ArrayList<CategoryEntity> menus) {
            this.selectPosition = 0;
            this.menus = menus;
        }

        @NonNull
        @Override
        public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
            Context context = viewGroup.getContext();
            TextView textView = new TextView(context);
            textView.setBackgroundResource(R.drawable.checkbox_border_primary);
            textView.setTextSize(TypedValue.COMPLEX_UNIT_PX, textSize);
            textView.setTextColor(colorStateList);
            textView.setGravity(Gravity.CENTER);
            RecyclerView.LayoutParams lp = new RecyclerView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, height);
            textView.setLayoutParams(lp);
            textView.setOnClickListener(listener);
            return new ViewHolder(textView);
        }

        @Override
        public void onBindViewHolder(@NonNull RecyclerView.ViewHolder viewHolder, int i) {
            CategoryEntity menu = menus.get(i);
            ViewHolder ho = (ViewHolder) viewHolder;
            TextView textView = (TextView) ho.itemView;
            textView.setSelected(i == selectPosition);
            textView.setText(menu.getName());
            textView.setTag(i);
        }

        @Override
        public int getItemCount() {
            return menus.size();
        }

        @Override
        public ArrayList<CategoryEntity> getList() {
            return menus;
        }

        public void updatePosition(int position) {
            int oldPosition = selectPosition;
            selectPosition = position;
            notifyItemChanged(oldPosition);
            notifyItemChanged(selectPosition);
        }

        private static class ViewHolder extends RecyclerView.ViewHolder {
            public ViewHolder(@NonNull View itemView) {
                super(itemView);
            }
        }
    }

    private static class GoodsAdapter extends BaseMoveAdapter<GoodsEntity> {
        private ArrayList<GoodsEntity> goodsList;
        private final View.OnClickListener listener;
        private final RequestOptions options;
        private final int imageSize;

        public GoodsAdapter(ArrayList<GoodsEntity> goodsList, int imageSize, int radius, View.OnClickListener listener) {
            this.goodsList = goodsList;
            this.listener = listener;
            this.imageSize = imageSize;
            this.options = new RequestOptions().transform(new CenterCrop(),
                            new CornersRoundedTransformation(radius, true))
                    .override(imageSize, imageSize)
                    .format(DecodeFormat.PREFER_RGB_565)
                    .diskCacheStrategy(DiskCacheStrategy.ALL);
        }

        @NonNull
        @Override
        public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
            View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.item_menu_product,
                    viewGroup, false);
            v.setOnClickListener(listener);
            ViewHolder viewHolder = new ViewHolder(v);
            LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) viewHolder.imageView.getLayoutParams();
            layoutParams.width = imageSize;
            layoutParams.height = imageSize;
            return viewHolder;
        }

        @Override
        public void onBindViewHolder(@NonNull RecyclerView.ViewHolder viewHolder, int i) {
            GoodsEntity goods = goodsList.get(i);
            ViewHolder ho = (ViewHolder) viewHolder;
            ho.nameView.setText(goods.getName());
            System.out.println("加载 " + goods.getName() + " 图片：" + goods.getIcon());
            Glide.with(ho.imageView)
                    .asBitmap()
                    .load(goods.getIcon())
                    .apply(options)
                    .into(ho.imageView);
            ho.itemView.setTag(goods);
        }

        @Override
        public int getItemCount() {
            return goodsList == null ? 0 : goodsList.size();

        }

        @Override
        public ArrayList<GoodsEntity> getList() {
            return goodsList;
        }

        public void updateList(ArrayList<GoodsEntity> list) {
            this.goodsList = list;
            notifyDataSetChanged();
        }

        private static class ViewHolder extends RecyclerView.ViewHolder {
            TextView nameView;
            ImageView imageView;

            public ViewHolder(@NonNull View itemView) {
                super(itemView);
                nameView = itemView.findViewById(R.id.name);
                imageView = itemView.findViewById(R.id.image);
            }
        }
    }

}
